<template>
  <div style="height:400px">
    <div class="page-body">
      <Toolbar
        class="page-toolbar"
        :editorId="editorId"
        :defaultConfig="toolbarConfig"
        mode="default"
      />
      <Editor
        class="page-editor"
        :editorId="editorId"
        :default-config="editorConfig"
        :default-html="defaultHtml"
        mode="default"
      />
    </div>
  </div>
</template>

<script lang="ts" >
import { defineComponent } from "vue";
import "@wangeditor/editor/dist/css/style.css";
export default defineComponent({
  name: "MyWangeditor"
});
</script>

<script lang="ts" setup>
import { withDefaults, ref, computed, reactive, onBeforeUnmount, } from "vue";
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import { v4 } from "uuid";
import { uploadFile } from "@/utils/api";
import { FILE_URL } from "@/config";

let props = withDefaults(defineProps<{
  /**
   * 默认展示数据
   * 数据只能为 editor getData中的数据
   * 不支持异步数据, 如果有需要可以添加v-if让defaultHtml 和 组件同时展示
   */
  defaultHtml?: string;

  /**
   * 业务类型
   */
  docType: string
}>(), {
  defaultHtml: ""
})

/**
 * 全局唯一id
 */
let editorId = ref(`wang-${v4()}`);

/**
 * 工具栏配置信息
 */
let toolbarConfig = reactive({
  //配置工具栏
  toolbarKeys: ["headerSelect", "color", "bgColor", "fontSize", "|", "bulletedList", "numberedList", "divider", "|", 'justifyLeft', 'justifyRight', 'justifyCenter', 'justifyJustify', "|", 'indent', 'delIndent', "|", "insertLink", 'insertImage', 'uploadImage', "insertVideo", "|", "undo", "redo"],
});
//     "@wangeditor/editor": "~0.15.11",
// "@wangeditor/editor-for-vue": "~5.1.11",
/**
 * 编辑框 配置信息 
 */
let editorConfig = reactive<any>({
  placeholder: '请在此处输入内容',
  MENU_CONF: {

  }
})

/**
 * 自定义上传图片组件
 */
editorConfig.MENU_CONF['uploadImage'] = {
  // 自定义上传
  async customUpload(file: File, insertFn: any) {
    // file 即选中的文件
    let res = await uploadFile(file, props.docType, {
      isImage: true
    })
    // 最后插入图片
    insertFn(FILE_URL + res.fileEntity, res.fileName);
  }
}

/**
 * 获取数据
 */
function getHtml() {
  const editor = getEditor(editorId.value)
  if (editor == null) return;
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = getEditor(editorId.value)
  if (editor == null) return

  editor.destroy()
  removeEditor(editorId.value)
})

defineExpose({
  getHtml
})
</script>

<style lang="less" scoped>
.page-body {
  height: 100%;
  border: 1px solid #ccc;
  display: flex;
  flex-direction: column;
}
.page-toolbar {
  flex-shrink: 0;
  border-bottom: 1px solid #ccc;
}
.page-editor {
  height: 0;
  flex-grow: 1;
  overflow-y: hidden;
}
</style>